import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { isLoading } from '../utils/loading';
import { useStore } from 'vuex';
import { key } from '../store/index';

// 定义路由规则
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: '/login' //默认重定向到登录页
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../pages/Login.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../pages/Register.vue')
    },
    {
        path: '/helloworld',
        name: 'HelloWorld',
        component: () => import('../components/HelloWorld.vue')
    },
    {
        path: '/xuesheng',
        name: 'Test',
        component: () => import('../components/XueSheng.vue')
    }
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
})

// 模拟登录状态存储
// const isAuthenticated = () => {
//     return localStorage.getItem('isLoggedIn') === 'true';
// }

// 添加导航守卫控制loading状态
router.beforeEach((to, from, next) => {
    isLoading.value = true;
    const store = useStore(key);
    const isAuthenticated = store.getters.isAuthenticated;
    // 已登录但尝试访问登录页面，重定向到首页
    if (to.path === '/login' && isAuthenticated) {
        next('/helloworld');
        return;
    }
    // 不需要验证的页面白名单
    const whiteList = ['/login', '/register'];
    // 检查当前页面是否在白名单中
    if (whiteList.includes(to.path)) {
        // 白名单页面直接放行
        next();
        return;
    }
    if (!isAuthenticated) {
        // 非白名单页面且未登录，重定向到登录页
        next('/login');
        return;
    }
    // 其它情况正常跳转
    next();
});

router.afterEach(() => {
    // 使用setTimeout确保loading效果能够被看到
    setTimeout(() => {
        isLoading.value = false;
    }, 300);
})

// 导出路由实例
export default router